import datetime

import pandas as pd
import matplotlib.pyplot as plt
import statistics

# 替换为你的Excel文件路径
file_path = '../../../asset/data/2024_weight.xlsx'
# 使用pandas的read_excel函数读取文件
all_sheet = pd.read_excel(file_path, sheet_name=None, keep_default_na=False)

# 获取当前日期时间
now = datetime.datetime.now()

# 格式化日期时间为字符串
date_str = now.strftime("%Y%m%d_%H%M")


def get_w2(w2):
    if w2:
        return w2
    else:
        return 0


for sheet_name, sheet_dframe in all_sheet.items():
    # print("======")
    # print(f"sheet_key:{sheet_name}月数据")
    rq = []  # 日期
    weight = []  # 体重

    # 过滤没有数据的行
    single_df = sheet_dframe.dropna(how="all")

    for index, row in single_df.iterrows():
        if row['日期']:
            # print(f'当前行={index},日期列值={row['日期']},体重1={row['体重1']},体重2={row['体重2']}')
            s = []
            if get_w2(row['体重1']) != 0:
                s.append(get_w2(row['体重1']))
            if get_w2(row['体重2']) != 0:
                s.append(get_w2(row['体重2']))

            if len(s) > 0:
                avg = round(statistics.mean(s), 1)
                if avg != 0:
                    rq.append(str(row['日期'])[4::])
                    weight.append(avg)

    if len(rq) > 0 and len(weight) > 0:
        # plt.plot(rq, weight, 'r-.')
        plt.plot(rq, weight)
        for a, b in zip(rq, weight):
            plt.text(a, b, str(b))
        plt.title(sheet_name)
        plt.xticks(rotation=45)
        # plt.xlabel('date')
        # plt.ylabel('avg-weight')
        plt.tight_layout()
        # plt.show()
        # plt.savefig(f'weight_lost_{date_str}.png')
        # plt.savefig(f'weight_lost_{sheet_name}.png')  # 生成文件名字
        plt.savefig(f'BLUE_{sheet_name}.png')  # 生成文件名字
        plt.close()  # 需要清空后再生成
    else:
        print(f'{sheet_name}体重数据数量{len(weight)}')
        print(f'{sheet_name}日期数据数量{len(rq)}')

    rq.clear()
    weight.clear()
